//
//  AppDelegate.m
//  BSProject
//
//  Created by nsm on 2019/6/17.
//  Copyright © 2019 beisheng. All rights reserved.
//

#import "AppDelegate.h"
#import "ViewController.h"
#import "OriViewController.h"
#import "RootController.h"
#import "ZRLController.h"

static NSString * const kSaltAES256 = @"4T9IpnNr8ajp1xZv";

@interface AppDelegate ()

@end

@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [AppSettings setup];
    [self setupNotifications];

    UIColor *color = UIColor.systemGroupedBackgroundColor;
    NSLog(@"hexString:%@", color.hexString);
    NSLog(@"hexStringWithAlpha:%@", color.hexStringWithAlpha);
    NSLog(@"myHexString:%@", color.myHexString);
    
    color = UIColor.groupTableViewBackgroundColor;
    NSLog(@"hexString:%@", color.hexString);
    NSLog(@"hexStringWithAlpha:%@", color.hexStringWithAlpha);
    NSLog(@"myHexString:%@", color.myHexString);


    self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
    self.window.backgroundColor = UIColor.whiteColor;
    //self.window.rootViewController = [NSMNavigationController controller:ZRLController.new];
    // self.window.rootViewController = RootController.new;
    self.window.rootViewController = [NSMNavigationController controller:ViewController.new];

    [self.window makeKeyAndVisible];
    
    return YES;
}

#pragma mark - 通知
- (void)userDidLogin:(NSNotification *)note {
    // 登录这里不要做root切换,因为很多场景是随时登录
}

- (void)userDidLogout:(NSNotification *)note {
    // 登出事件已经清理了缓存只需要重置根控制器
    [self resetRootController];
}

- (void)userPasswordDidChange:(NSNotification *)note {
    // 修改密码|忘记密码 仅仅发出了通知,需清理缓存
    [self clearAndReset];
}

- (void)userDidDenied:(NSNotification *)note {
    // 多一个弹窗
    NSString *message = ReplaceString(note.object, InternationalString(@"您的账号存在异常,请重新登录"));
    [[NSMUtilities topViewController] showAlert:message action:^(UIAlertAction *action) {
        [self clearAndReset];
    }];
}

- (void)clearAndReset {
    _keyWindow.isLoading = YES;
    @nsm_weak(self)
    [_appCache clearUserInfo:^{
        @nsm_strong(self)
        dispatch_async(dispatch_get_main_queue(), ^{
            _keyWindow.isLoading = NO;
            [self resetRootController];
        });
    }];
}

- (void)resetRootController {
    LoginController *login = LoginController.new;
    @nsm_weak(self)
    login.didLoginSuccess = ^(id data) {
        @nsm_strong(self)
        // self.window.rootViewController = self.tabBarController;
    };
    self.window.rootViewController = [NSMNavigationController controller:login];
    // 防止当前window不是keyWindow
    [self.window makeKeyAndVisible];
}

@end
